package com.lishem.top100._08tree;

import com.lishem.common.TreeNode;

/**
 * https://leetcode.cn/problems/path-sum-iii/
 * <p>
 * 给定一个二叉树的根节点root，和一个整数targetSum，求该二叉树里节点值之和等于targetSum的路径的数目。
 * <p>
 * 路径不需要从根节点开始，也不需要在叶子节点结束，但是路径方向必须是向下的（只能从父节点到子节点）。
 */
public class _13LetCode437_路径总和3 {


    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return 0;
        }
        long ts = (long) targetSum;
        int res = rootSum(root, ts);
        res += pathSum(root.left, targetSum);
        res += pathSum(root.right, targetSum);
        return res;
    }

    public int rootSum(TreeNode root, long targetSum) {
        int res = 0;
        if (root == null) {
            return 0;
        }
        if (root.val == targetSum) {
            res++;
        }
        res += rootSum(root.left, targetSum - root.val);
        res += rootSum(root.right, targetSum - root.val);
        return res;
    }

    public static void main(String[] args) {
        _13LetCode437_路径总和3 sol = new _13LetCode437_路径总和3();
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.left.left = new TreeNode(3);
        root.left.left.left = new TreeNode(3);
        root.left.left.right = new TreeNode(-2);
        root.left.right = new TreeNode(2);
        root.left.right.right = new TreeNode(1);
        root.right = new TreeNode(-3);
        root.right.right = new TreeNode(11);
        System.out.println(sol.pathSum(root, 8));
    }
}
